var fs = require('fs');
var qs = require('querystring');

//代理处理响应
function route(handle,urlObject,response){
    let pathname = urlObject.pathname;
    if(typeof handle[pathname] === 'function'){ //
        let request = qs.parse(urlObject.query);
        handle[pathname](request,response);
    }else if(checkPath(pathname)){ //请求静态文件
		fs.createReadStream(__dirname+pathname).pipe(response);
	}else{ //没找到相关静态文件
		response.writeHeader(404,{'Content-Type':'text/html;  charset=utf-8'});
		fs.createReadStream(__dirname+"/web/notfind.html").pipe(response);
    }
}

//检查请求的静态资源是否包含在静态路径中
function checkPath(pathname){
	let fileName = pathname.split('/').pop();
	let fileType = fileName.split('.').pop();
	let list = null;
	try{
		list = fs.readdirSync(__dirname + '/web/' + fileType);
	}catch(e){
		return false;
	}
	return list.indexOf(fileName) != -1;
}

module.exports = {
    route : route
};